using System;
using System.Net;
using FtpLib;

namespace Quiki.Services
{
    public class FtpLibFtpClient : IFtpClient
    {
        public string Host
        {
            get { return host; }
            set { host = value; }
        }

        public int? Port
        {
            get { return port; }
            set { port = value; }
        }

        public ICredentials Credentials { get; set; }

        public IFtpConnection Open()
        {
            ValidateParameters();

            FtpConnection ftpConnection;

            NetworkCredential networkCredential = (NetworkCredential)Credentials;

            if (port.HasValue)
                ftpConnection = new FtpConnection(host, port.Value, networkCredential.UserName, networkCredential.Password);
            else
                ftpConnection = new FtpConnection(host, networkCredential.UserName, networkCredential.Password);

            ftpConnection.Open();
            ftpConnection.Login();

            return new FtpLibFtpConnection(ftpConnection);
        }

        private void ValidateParameters()
        {
            if (Credentials == null)
                throw new ArgumentException("FTP credentials were not specified");

            if (false == Credentials is NetworkCredential)
                throw new ArgumentException("Only NetworkCredentials are currently supported");

            NetworkCredential networkCredential = (NetworkCredential) Credentials;

            if (string.IsNullOrEmpty(host))
                throw new ArgumentException("FTP host is not specified");

            if (string.IsNullOrEmpty(networkCredential.UserName))
                throw new ArgumentException("FTP user name is not specified");

            if (string.IsNullOrEmpty(networkCredential.Password))
                throw new ArgumentException("FTP password is not specified");
        }

        private string host;
        private int? port;
    }
}